import android.content.Context
import android.content.Intent
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zuoent.silver.SingletonHolder
import io.flutter.plugin.common.MethodChannel

class WeixinClient private constructor(context: Context) {
    private val appId = "wxeb82b4d3ad99bee2"
    private val api: IWXAPI
    private var loginResult: MethodChannel.Result? = null

    init {
        api = WXAPIFactory.createWXAPI(context, appId, true)
        api.registerApp(appId)
    }

    fun handleIntent(intent: Intent, handler: IWXAPIEventHandler) {
        api.handleIntent(intent, handler)
    }

    fun requestLogin(result: MethodChannel.Result) {
        loginResult = result

        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"

        api.sendReq(req)
    }

    fun onLoginSuccess(code: String) {
        loginResult!!.success(code)
    }

    companion object : SingletonHolder<WeixinClient, Context>(::WeixinClient)
}